package online.shenme.day14_self.dao;

import online.shenme.day14_self.domin.Subway;

import java.io.*;
import java.util.HashMap;


public class SubwaysDAO implements DAO<String, Subway> {

    private static final HashMap<String, Subway> swMap = new HashMap<>();
    private static BufferedWriter bw;
    private static BufferedReader br;

    public SubwaysDAO() {
        try {
            bw = new BufferedWriter(new FileWriter("javaadvance/src/online/shenme/day14_self/domin/subways.txt",true));
            br = new BufferedReader(new FileReader("javaadvance/src/online/shenme/day14_self/domin/subways.txt"));
            String s;
            while ((s = br.readLine()) != null) {
                bw.write(s);
                bw.newLine();
                String[] split = s.split(",");
                swMap.put(split[0], new Subway(split[0], split[1], split[2]));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void closeBW(){

    }
    @Override
    public HashMap<String, Subway> findAll() {
        return swMap;
    }

    @Override
    public boolean delete(String id) {
        return false;
    }

    @Override
    public boolean reSet(String id, Subway subway) {
        return false;
    }

    @Override
    public boolean add(String s, Subway subway) {
        if (getById(s) == null) {
            try {
                bw.write(subway.getCode() + "," + subway.getName() + "," + subway.getBelong());
                bw.newLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return swMap.put(s, subway) == null;
        }
        return false;
    }

    @Override
    public Subway getById(String id) {
        return swMap.get(id);
    }

    public static void close() throws IOException {
        bw.close();
    }
}
